<template>
  <div id="app">
    <div v-if="books.length">
      <!--购物车内容列表 -->
    </div>
    <h2 v-else>
      购物车为空
    </h2>
    <table border="1" align="center" width="500">
      <caption>
        <h2>购物车</h2>
      </caption>
      <thead>
        <tr>
          <th></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in books" :key="index" align="center">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ filter(item.price) }}</td>
          <td>
            <button @click="decrement(index)" v-bind:disabled="item.count <= 0">
              -
            </button>
            {{ item.count }}
            <button @click="increment(index)">+</button>
          </td>
          <td>
            <button @click="removeHandle(index)">移除</button>
          </td>
        </tr>
        <tr align="center">
          <td colspan="2">总价格</td>
          <td colspan="3">{{ filter(computedName) }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import { reactive, toRefs, computed } from "vue";

export default {
  setup() {
    const state = reactive({
      books: [
        // 定义图书对象数组
        {
          id: 1,
          name: "华为mate30",
          price: 3465,
          count: 2,
        },
        {
          id: 2,
          name: "华为mate40",
          price: 4166,
          count: 3,
        },
        {
          id: 3,
          name: "苹果12",
          price: 7500,
          count: 2,
        },
        {
          id: 4,
          name: "OPPO",
          price: 2180,
          count: 4,
        },
      ],
    });
    const decrement = (index) => {
      state.books[index].count--; // index指定图书对象的id值减１
    };
    const increment = (index) => {
      state.books[index].count++; // index指定图书对象的id值加１
    };
    const removeHandle = (index) => {
      state.books.splice(index, 1); // 删除index指定的图书对象
      for (let i = 0; i < state.books.length; i++) {
        state.books[i].id = i + 1; // 重新排序计算所含数据的id值
      }
    };
    const filter = (price) => {
      return "￥" + price.toFixed(2);
    };
    const computedName = computed(() => {
      let totalPrice = 0; // 初始化总价为０
      for (let i = 0; i < state.books.length; i++) {
        // 把数组中的每个元素的价格*数量，再相加到totalPrice
        totalPrice += state.books[i].price * state.books[i].count;
      }
      return totalPrice; // 返回总价
    });
    return {
      ...toRefs(state),
      computedName,
      decrement,
      increment,
      removeHandle,
      filter,
    };
  },
};
</script>

<style scoped></style>
